package com.ruoyi.biz.imported.strategy;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ReUtil;
import cn.hutool.extra.tokenizer.TokenizerEngine;
import cn.hutool.extra.tokenizer.TokenizerUtil;
import cn.hutool.extra.tokenizer.Word;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.ruoyi.biz.imported.vo.ReqVO;
import com.ruoyi.biz.letter.domain.BizCityLetter;
import com.ruoyi.biz.letter.mapper.BizCityLetterMapper;
import com.ruoyi.biz.letter.util.SysDeptUtil;
import com.ruoyi.biz.plan.domain.BizPlanConfig;
import com.ruoyi.biz.plan.mapper.BizPlanConfigMapper;
import com.ruoyi.common.enums.LetterStatus;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.enums.ValidType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.BatchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Fei.Cong
 * @date 2024-07-17 14:32
 */
@Slf4j
@Service
public class CityRegisterStrategy implements ImportedStrategy {

    @Autowired
    private BizCityLetterMapper bizCityLetterMapper;

    public static void main(String[] args) {
        System.out.println(DateUtil.format(new Date(), "yyyy-MM"));

    }

    @SneakyThrows
    @Override
    public String importHandleData(ReqVO reqVO) {

        ExcelUtil<BizCityLetter> util = new ExcelUtil<BizCityLetter>(BizCityLetter.class);
//        Validator.validateNotEmpty(reqVO.getBillMonth(), "请选择月份");
        List<BizCityLetter> citySheet1List = util.importEasyExcel(reqVO.getFile().getInputStream(), 0, 1);
//        List<BizCityLetter> citySheet2List = util.importEasyExcel(reqVO.getFile().getInputStream(), 1, 2);

//        if (CollectionUtil.isEmpty(citySheet1List) && CollectionUtil.isEmpty(citySheet2List)) {
        if (CollectionUtil.isEmpty(citySheet1List)) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int existNum = 0;
//        citySheet1List.addAll(citySheet2List);
        StringBuilder msg = new StringBuilder();

        if (!reqVO.isUpdateSupport()) {
            List<BizCityLetter> insertCityLetterList = Lists.newArrayList();
            List<Long> ids = Lists.newArrayList();
            for (BizCityLetter cityLetter : citySheet1List) {
                try {
                    QueryWrapper<BizCityLetter> queryWrapper = new QueryWrapper<>();
                    queryWrapper.select("id", "letter_number", "is_reasonable", "is_solve", "is_finish", "owner_area").eq("letter_number", cityLetter.getLetterNumber());
                    BizCityLetter entity = bizCityLetterMapper.selectOne(queryWrapper);

                    if (Objects.nonNull(entity)) {
                        if (Objects.nonNull(entity.getIsReasonable()) || Objects.nonNull(entity.getIsFinish()) || Objects.nonNull(entity.getIsSolve())) {
                            failureNum++;
                            msg.append("<br/>" + failureNum + "、信访件编号 " + cityLetter.getLetterNumber() + " <font color='red'>已认领</font>");
                            continue;
                        } else {
                            ids.add(entity.getId());
                            existNum++;
                            msg.append("<br/>" + existNum + "、信访件编号 " + cityLetter.getLetterNumber() + " <font color='blue'>已更新</font>");
                        }
                    } else {
                        successNum++;
                        msg.append("<br/>" + successNum + "、信访件编号 " + cityLetter.getLetterNumber() + " <font color='green'>已导入</font>");
                    }
                    cityLetter.setDeptId(SysDeptUtil.getDeptId(cityLetter.getLetterNumber(), cityLetter.getOwnerArea()));
                    cityLetter.setBillMonth(DateUtil.format(cityLetter.getLetterTime(), "yyyy-MM"));
                    cityLetter.setStatus(LetterStatus.WAIT_CLAIM.getCode());
                    insertCityLetterList.add(cityLetter);
                } catch (Exception e) {
                    failureNum++;
                    String emsg = "<br/>" + failureNum + "、信访件编号 " + cityLetter.getLetterNumber() + " 导入失败：";
                    msg.append(emsg + e.getMessage());
                    log.error(emsg, e);
                }
            }
            if (CollectionUtil.isNotEmpty(ids)) {
                bizCityLetterMapper.deleteByIds(ids);
            }
            bizCityLetterMapper.insert(insertCityLetterList);
        }

        msg.insert(0, "操作成功！成功 " + successNum + " 条，更新 " + existNum + " 条，失败 " + failureNum + " 条，数据如下：");

        return msg.toString();
    }

}
